package model

import "gorm.io/gorm"

type Article struct {
	gorm.Model
	Category Category `gorm:"foreignKey:Cid"`
	Title    string   `gorm:"type:varchar(100);not null" json:"title"`
	Cid      int      `gorm:"type:int;not null" json:"cid"`
	Desc     string   `gorm:"type:varchar(200);not null" json:"desc"`
	Content  string   `gorm:"type:longtext;not null" json:"content"`
	Img      string   `gorm:"type:varchar(100);not null" json:"img"`
}

func (this *Article) TableName() string {
	return "article"
}

func (this *Article) Get() error {
	return db.Where("id = ?", this.ID).First(this).Error
}
func (this *Article) Create() (int64, error) {
	tx := db.Omit("created_time").Create(this)
	return tx.RowsAffected, tx.Error
}
func (this *Article) Update(m map[string]interface{}) (int64, error) {
	tx := db.Model(this).Where("id = ?", this.ID).Omit("password").Updates(m)
	return tx.RowsAffected, tx.Error
}
func (this *Article) Delete() (int64, error) {
	tx := db.Model(this).UpdateColumn("deleted", 1)
	return tx.RowsAffected, tx.Error
}
func (this *Article) Remove() (int64, error) {
	tx := db.Unscoped().Delete(this)
	return tx.RowsAffected, tx.Error
}
func GetArticleList(pageSize, pageNum int) (articles []Article, err error) {
	var (
		total int64
	)
	err = db.Limit(pageSize).Offset((pageNum - 1) * pageSize).Find(&articles).Error
	db.Model(&User{}).Count(&total)
	if err != nil && err != gorm.ErrRecordNotFound {
		return
	}
	return articles, nil
}
